<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="科室名" prop="departmentName">
        <el-input
          v-model="queryParams.departmentName"
          placeholder="请输入科室名"
          clearable
        />
      </el-form-item>
      <el-form-item label="科室状态" prop="departmentStatus">
        <el-select
          v-model="queryParams.departmentStatus"
          placeholder="请选择科室状态"
          clearable
          @focus="getDictData"
        >
          <el-option
            v-for="status in departmentStatusOptions"
            :key="status.dictValue"
            :label="status.dictLabel"
            :value="status.dictValue"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:department:add']"
          >新增</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="departmentList"
      row-key="departmentId"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column label="科室名" align="center" prop="departmentName">
        <template slot-scope="scope">
          <span
            :style="{
              paddingLeft: `${scope.row.level * 20}px`,
              fontWeight: scope.row.level ? 'normal' : 'bold',
            }"
          >
            {{ scope.row.departmentName }}
          </span>
        </template>
      </el-table-column>

      <el-table-column
        label="科室描述"
        align="center"
        prop="departmentDescription"
      />

      <!-- 状态列 -->
      <el-table-column label="状态" align="center" prop="departmentStatus">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.departmentStatus"
            :active-value="0"
            :inactive-value="1"
            active-text="启用"
            inactive-text="禁用"
            :active-color="'#67C23A'"
            :inactive-color="'#F56C6C'"
            :disabled="
              !canChangeStatus(scope.row) || isAncestorDisabled(scope.row)
            "
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:department:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            :disabled="scope.row.children && scope.row.children.length > 0"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:department:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      :title="title"
      :visible.sync="open"
      width="500px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="" prop="departmentId" />
        <el-form-item label="科室名" prop="departmentName">
          <el-input v-model="form.departmentName" placeholder="请输入科室名" />
        </el-form-item>
        <el-form-item label="科室描述" prop="departmentDescription">
          <el-input
            v-model="form.departmentDescription"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <!-- 父级科室下拉框只有在需要时才显示 -->
        <el-form-item
          v-if="showParentSelect"
          label="所属父级科室"
          prop="departmentParentId"
        >
          <el-select
            v-model="form.departmentParentId"
            placeholder="不选择默认是父级科室"
          >
            <el-option
              v-for="item in departmentOptions"
              :key="item.departmentId"
              :label="item.departmentName"
              :value="item.departmentId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getDepartmentList,
  updateDepartmentStatus,
  addDepartment,
  getParentDepartment,
  updateDepartment,
  delDepartment,
} from "@/api/medicalManament/department";
import { getDicts } from "@/api/system/dict/data";
export default {
  name: "Department",
  data() {
    return {
      loading: true,
      ids: [],
      showSearch: true,
      departmentList: [],
      title: "",
      open: false,
      queryParams: {
        departmentName: null,
        departmentStatus: null, // 添加科室状态查询参数
      },
      form: {},
      rules: {
        departmentName: [
          { required: true, message: "科室名不能为空", trigger: "blur" },
        ],
        departmentDescription: [
          { required: true, message: "科室描述不能为空", trigger: "blur" },
        ],
      },
      departmentOptions: [],
      departmentStatusOptions: [],
      showParentSelect: true, // 控制父级科室下拉是否显示
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 查找科室状态字典
    getDictData() {
      getDicts("department_status").then((response) => {
        console.log("科室状态数据", response);
        this.departmentStatusOptions = response.data;
      });
    },
    getParentDepartments() {
      getParentDepartment().then((response) => {
        this.departmentOptions = response.data;
      });
    },
    canChangeStatus(row) {
      if (!row.children || row.children.length === 0) return true;
      return row.children.every((child) => {
        if (child.departmentStatus === 0) return false;
        return this.canChangeStatus(child);
      });
    },
    isAncestorDisabled(row) {
      let pid = row.departmentParentId;
      while (pid !== null && pid !== undefined) {
        const parent = this.findNodeById(this.departmentList, pid);
        if (!parent) break;
        if (parent.departmentStatus === 1) return true;
        pid = parent.departmentParentId;
      }
      return false;
    },
    findNodeById(list, id) {
      if (!Array.isArray(list)) return null;
      for (const node of list) {
        if (node.departmentId === id) return node;
        const found = this.findNodeById(node.children || [], id);
        if (found) return found;
      }
      return null;
    },
    getList() {
      this.loading = true;
      getDepartmentList(this.queryParams).then((res) => {
        console.log(res);
        if (res.data.code !== 200) {
          this.$message.error("获取科室列表失败");
          this.loading = false;
          return;
        }
        this.departmentList = res.data.data.list;
        this.loading = false;
      });
    },
    handleStatusChange(row) {
      const statusText = row.departmentStatus === 0 ? "启用" : "禁用";
      const confirmMessage = `确认要${statusText}科室 "${row.departmentName}" 吗？`;
      this.$modal
        .confirm(confirmMessage)
        .then(() => {
          updateDepartmentStatus(row.departmentId).then((res) => {
            console.log("科室状态更改", res);
            if (res.data.code === 200) {
              this.$message.success(`状态已${statusText}`);
            } else {
              this.$message.error("状态更改失败");
            }
            this.getList();
          });
        })
        .catch(() => {
          this.$message.info("操作已取消");
          row.departmentStatus = row.departmentStatus === 1 ? 0 : 1;
        });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        departmentId: null,
        departmentName: null,
        departmentDescription: null,
        departmentParentId: null,
      };
      this.resetForm("form");
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加科室";
      this.showParentSelect = true; // 新增时总显示父级选择
      this.getParentDepartments();
    },
    handleUpdate(row) {
      this.reset();
      this.open = true;
      this.title = "修改科室";
      this.form = { ...row };
      this.showParentSelect = !!row.departmentParentId; // 顶级科室不显示父级选择
      if (this.showParentSelect) {
        this.getParentDepartments();
      }
    },
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.departmentId != null) {
            updateDepartment(this.form).then((res) => {
              console.log(res);
              if (res.data.code === 200) {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.$modal.msgError("科室名已存在，请重新输入");
              }
            });
          } else {
            addDepartment(this.form).then((response) => {
              if (response.data.code === 200) {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.reset();
              } else {
                this.$modal.msgError("新增失败,科室名已存在,请重新输入");
                this.reset();
              }
              this.getList();
            });
          }
        }
      });
    },
    handleDelete(row) {
      const departmentIds = row.departmentId || this.ids;
      this.$modal
        .confirm(`是否确认删除"${row.departmentName}"科室吗？`)
        .then(() => {
          return delDepartment(departmentIds);
        })
        .then((res) => {
          console.log(res);
          if (res.data.code === 200) {
            this.getList();
            this.$modal.msgSuccess("删除成功");
          } else {
            this.$modal.msgError("删除失败，该科室下有医生，无法删除");
          }
        });
    },
  },
};
</script>

<style scoped>
.el-table .level-0 {
  font-weight: bold;
}
.el-table .level-1 {
  font-weight: normal;
}
</style>
